// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 创建集合
    const collections = ['recipes', 'familyMembers', 'foodItems']
    for (const collection of collections) {
      try {
        await db.createCollection(collection)
        console.log(`创建集合成功: ${collection}`)
      } catch (err) {
        if (err.errCode === -501001) {
          console.log(`集合已存在: ${collection}`)
        } else {
          throw err
        }
      }
    }

    // 创建索引
    await db.collection('recipes').createIndex({
      data: {
        createTime: -1
      }
    })

    await db.collection('foodItems').createIndex({
      data: {
        name: 1
      }
    })

    return {
      success: true,
      message: '数据库初始化成功'
    }
  } catch (error) {
    console.error('数据库初始化失败', error)
    return {
      success: false,
      message: error.message
    }
  }
} 